package pers.cz.chat.ui;

import pers.cz.chat.utils.FlashUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @description:
 * @author: ChengZhi 0336
 * @create: 2025-01-24 17:07
 **/
public class ChatUi {
	private static PrintWriter printWriter;

	private static Process process;

	private static final String NORMAL_ICON_PATH = "icons/feishu.png"; // 设置为你的正常图标路径

	private JPanel frame;

	private String filePath;

	public void setSourceFilePath(String filePath) {
		this.filePath = filePath;
	}
	public JPanel getComponent() {
		return this.frame;
	}

	public ChatUi() {

		// 设置系统托盘图标
		if (!SystemTray.isSupported()) {
			System.out.print("System tray is not supported!");
			return;
		}

		// 创建 JFrame
		frame = new JPanel(new BorderLayout());

		// 创建 JTextArea 用于显示 CMD 输出
		JTextArea textArea = new JTextArea();
		// 设置背景
		//textArea.setBackground(Color.BLACK);
		textArea.setForeground(Color.WHITE);
		textArea.setEditable(false);
		// 启用自动换行
		textArea.setLineWrap(true);           // 启用自动换行
		textArea.setWrapStyleWord(true);      // 按单词换行

		JScrollPane scrollPane = new JScrollPane(textArea);

		// 禁用水平滚动条
		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		frame.add(scrollPane, BorderLayout.CENTER);

		// 创建输入框
		JTextField textField = new JTextField();
		frame.add(textField, BorderLayout.SOUTH);

		// 创建系统托盘图标
		FlashUtils flashUtils = new FlashUtils(frame);
		flashUtils.createTrayIcon();
		// 启动 CMD 进程
		startCmdProcess(textArea, flashUtils);

		// 处理用户输入
		textField.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String command = textField.getText();
				if (!command.trim().isEmpty()) {

					if (command.startsWith("-clear")) {
						textArea.setText("");
						textField.setText(""); // 清空输入框
						return;
					}

					textArea.append(command+ "\n");
					executeCommand(command);
					textField.setText(""); // 清空输入框
				}
			}
		});

		// 显示窗口
		frame.setVisible(true);

	}

	private static void startCmdProcess(JTextArea textArea, FlashUtils flashUtils) {
		try {
			String jarPath = "D:\\vue\\project\\jef-chat\\chat-client\\target\\chat-client-1.0-SNAPSHOT-start.jar";
			if (isJarRun()) {
				InputStream resourceAsStream = ChatUi.class.getClassLoader().getResourceAsStream("BOOT-INF/lib/chat-client-1.0-SNAPSHOT-start.jar");
				File jarFile = new File("client.jar");
				inputstreamtofile(resourceAsStream, jarFile);
				jarPath = jarFile.getPath();
			}


			java.util.List<String> commands = new ArrayList<String>();
			commands.add("java");
			if (javaVersionGt8()) {
				commands.add("--add-opens");
				commands.add("java.base/java.nio=ALL-UNNAMED");
			}
			commands.add("-jar");
			commands.add(jarPath);

			ProcessBuilder processBuilder = new ProcessBuilder(commands);
			processBuilder.redirectErrorStream(true);
			process = processBuilder.start();
			printWriter = new PrintWriter(new OutputStreamWriter(process.getOutputStream(), "UTF-8"), true);

			new Thread(() -> {

				try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"))) {
					String line;
					while ((line = reader.readLine()) != null) {
						textArea.append(line + "\n");
						textArea.setCaretPosition(textArea.getDocument().getLength());
						if (line.startsWith("收到")) {
							flashUtils.triggerTrayFlashing(); // 每次读取新行时触发托盘闪烁
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}).start();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void executeCommand(String command) {
		if (printWriter != null) {
			printWriter.println(command);
		}
	}

	private static void closeSubProcess() {
		if (process != null) {
			process.destroy();
			try {
				if (!process.waitFor(5, TimeUnit.SECONDS)) {
					process.destroyForcibly();
				}
			} catch (InterruptedException ie) {
				ie.printStackTrace();
			}
		}
	}

	public static void inputstreamtofile(InputStream ins, File file) throws IOException {
		OutputStream os = new FileOutputStream(file);
		int bytesRead;
		byte[] buffer = new byte[8192];
		while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		ins.close();
	}

	/**
	 * 判断是否为jar包运行
	 * @return
	 */
	private static boolean isJarRun() {
		try {
			Class.forName("com.intellij.rt.execution.application.AppMainV2");
			return false;
		} catch (ClassNotFoundException ignored) {
			return true;
		}
	}

	/**
	 * 判断java版本是否大于8
	 * @return
	 */
	private static boolean javaVersionGt8() {

		String version = System.getProperty("java.version");
		// 对于Java 9及以上的版本，版本字符串格式为 "9" 或者 "9.0.1" 等等
		// 对于Java 8及以下版本，版本字符串格式为 "1.8.0_XXX"
		if (version.startsWith("1.")) {
			int startIdx = version.indexOf('.') + 1;
			int endIdx = version.indexOf('.', startIdx);
			if (endIdx == -1) {
				endIdx = version.indexOf('_', startIdx);
			}
			if (endIdx == -1) {
				endIdx = version.length();
			}
			int majorVersion = Integer.parseInt(version.substring(startIdx, endIdx));
			return majorVersion > 8;
		} else {
			// Java 9 and above
			int dotIdx = version.indexOf('.');
			int majorVersion = dotIdx != -1 ? Integer.parseInt(version.substring(0, dotIdx)) : Integer.parseInt(version);
			return majorVersion > 8;
		}
	}
}
